import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UploadOutlined,
  UserOutlined,
  ExclamationCircleOutlined,
  AppstoreOutlined,
  PieChartOutlined,
} from '@ant-design/icons';
import { Layout, Menu, theme, Button, Modal, message } from 'antd';
import '@/assets/css/dashboard.css'
// 引入二级路由组件
import Admin from '@/router/admin';
import { Link } from 'react-router-dom';
// 获取用户信息
import { adminInfo, jwtPreCheck } from '@/api/dashboard'
import { useHistory, useLocation } from 'react-router-dom';

const { Header, Sider, Content } = Layout;
const Dashboard = () => {
  // console.log('首页')
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  // 获取 redux 仓库中的 store 数据 acl
  const { acl } = useSelector((state) => state)
  // console.log(acl);

  // 左侧 menu 
  function getItem(label, key, icon, children, type) {
    return {
      key,
      icon,
      children,
      label,
      type,
    };
  }

  const items = []
  acl.map((v, i) => {
    // 判断有没有二级菜单
    if (v.children.length != 0) {
      items.push(getItem(v.auth_name, v.auth_path, <AppstoreOutlined />, v.children.map((v1, i1) => {
        if (v1.is_nav === 1) {
          return getItem(<Link to={v1.auth_path} >{v1.auth_name}</Link>, v1.auth_path)
        }
      })))
    } else {
      items.push(getItem(<Link to={v.auth_path} >{v.auth_name}</Link>, v.auth_path, <PieChartOutlined />))
    }
  })

  const [accountInfo, setAccountInfo] = useState({})
  useEffect(() => {
    adminInfo().then(res => {
      // console.log('获取用户信息', res)
      setAccountInfo(res.data.accountInfo)
    })

    // 验证 token, 做防跳墙功能
    jwtPreCheck().then(res => {
      // console.log('进行 jwt 验证', res)
      if(res.data.errNo != 0) {
        message.error('请先登录', 1, () => {
          his.push('/login')
        })
      }
    })
  }, [])

  // 注销登录
  const his = useHistory()
  const dispatch = useDispatch()
  const loginOut = () => {
    Modal.confirm({
      title: '退出登录',
      icon: <ExclamationCircleOutlined />,
      content: '确认要退出登录吗?',
      okText: '确认',
      cancelText: '取消',
      onCancel: () => {},
      onOk: () => {
        console.log('点击确认')
        // 01: 清除 token
        localStorage.removeItem('jwt')
        // 02: 清除 acl
        dispatch({type: 'updateAcl', payload: []})
        localStorage.removeItem('persist:userAcl')
        // 返回登录页
        message.success('退出登录', 1, () => {
          his.push('/login')
        })
      }
    });
  }

  // 设置默认选中的菜单项defaultSelectedKeys key 对应的path 路径
  const loc = useLocation();
  // console.log('loc', loc)

  return (
    <Layout>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="logo" > </div>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={[loc.pathname]}
          defaultOpenKeys={[loc.pathname.substring(0, loc.pathname.lastIndexOf('/'))]}
          items={items}
        />
      </Sider>
      <Layout className="site-layout">
        <Header
          style={{
            padding: 0,
            background: colorBgContainer,
            display: 'flex',
            alignItems: 'center'

          }}
        >
          {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
            className: 'trigger',
            onClick: () => setCollapsed(!collapsed),
          })}
          <div style={{
            flex: 1,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            paddingLeft: '10px',
            paddingRight: '10px'
          }}>
            {/* 显示用户名角色 */}
            <span>您好: {accountInfo.username}/ {accountInfo.role}</span>
            {/* 注销登录 */}
            <Button onClick={loginOut} type="primary" ghost size='small'>
              退出登录
            </Button>
          </div>
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
            overflow: 'auto'
          }}
        >
          {/* 二级路由组件的坑 */}
          <Admin></Admin>
        </Content>
      </Layout>
    </Layout>
  );
}

export default Dashboard;
